﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.ComponentModel;
using System.Collections.ObjectModel;
using C1.Silverlight.DataGrid.Summaries;

namespace DYSales.Views.sell
{
    public partial class cwin_SellAdd : ChildWindow
    {
        ObservableCollection<Web.SellDetail> sts;
        public cwin_SellAdd()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(cwin_SellAdd_Loaded);
            tb_快速查询.Populating += new PopulatingEventHandler(tb_快速查询_Populating);
            tb_快速查询.AddHandler(KeyDownEvent, new KeyEventHandler(tb_快速查询_KeyDown), true);
            bt_指定单价.Click += new RoutedEventHandler(bt_指定单价_Click);
            cbb_分类.SelectionChanged += new SelectionChangedEventHandler(cbb_分类_SelectionChanged);
            bt_消费退单.Click += new RoutedEventHandler(bt_消费退单_Click);
            tb_数量.AddHandler(KeyDownEvent, new KeyEventHandler(tb_数量_KeyDown), true);
            bt_赠送.Click += new RoutedEventHandler(bt_赠送_Click);
            bt_选中加数量.Click += new RoutedEventHandler(bt_选中加数量_Click);
            bt_选中加一.Click += new RoutedEventHandler(bt_选中加一_Click);
            bt_选中减一.Click += new RoutedEventHandler(bt_选中减一_Click);
            tv_分类.AddHandler(MouseLeftButtonDownEvent, new MouseButtonEventHandler(tv_分类_MouseLeftButtonDown), true);
            bt_添加消费.Click += new RoutedEventHandler(bt_添加消费_Click);
            tb_快速查询.SelectionChanged += new SelectionChangedEventHandler(tb_快速查询_SelectionChanged);
            bt_刷新商品库.Click += new RoutedEventHandler(bt_刷新商品库_Click);
            KeyDown += new KeyEventHandler(cwin_SellAdd_KeyDown);
            tb_现金.ValueChanged += new RoutedPropertyChangedEventHandler<double>(tb_现金_ValueChanged);
            tb_信用卡.ValueChanged += new RoutedPropertyChangedEventHandler<double>(tb_信用卡_ValueChanged);
            tb_折扣.ValueChanged += new RoutedPropertyChangedEventHandler<double>(tb_析扣_ValueChanged);
            bt_挂提单.Click += new RoutedEventHandler(bt_挂提单_Click);
        }

        void bt_挂提单_Click(object sender, RoutedEventArgs e)
        {
            sellSaveLoad();
        }

        void tb_析扣_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (sts.Count == 0)
            {
                tb_折扣.Value = 1;
                return;
            }
            comput();
        }

        void tb_信用卡_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (sts.Count == 0)
            {
                tb_信用卡.Value = 0;
                return;
            }
            if (Convert.ToDecimal(tb_信用卡.Value) > sts.Sum(s => s.sd_小计))
            {
                tb_信用卡.Value = Convert.ToDouble(sts.Sum(s => s.sd_小计));
            }
            comput();
        }

        void tb_现金_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (sts.Count == 0)
            {
                tb_现金.Value = 0;
                return;
            }
            comput();
        }

        void comput()
        {
            tbk_实收.Text = (Convert.ToDouble(sts.Sum(s => s.sd_小计)) * tb_折扣.Value).ToString("0.##");
            tbk_找零.Text = ((tb_现金.Value + tb_信用卡.Value) - double.Parse(tbk_实收.Text)).ToString("0.##");
        }

        int s = 0;
        void cwin_SellAdd_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Tab)
            {
                if (s == 0)
                {
                    tb_现金.Focus();
                    s++;
                }
                else if (s == 1)
                {
                    tb_信用卡.Focus();
                    s++;
                }
                else if (s == 2)
                {
                    tb_折扣.Focus();
                    s++;
                }
                else
                {
                    tb_快速查询.Focus();
                    s = 0;
                }
                e.Handled = true;
            }
            else if (e.Key == Key.F8)
            {
                tb_数量.Focus();
            }
            else if (e.Key == Key.F9)
            {
                sellSaveLoad();
            }
            else if (e.Key == Key.Insert)
            {
                tb_快速查询.Focus();
                s = 0;
            }
            else if (e.Key == Key.Ctrl)
            {
                OKButton_Click(null, null);
            }
            else if (e.Key == Key.Escape)
            {
                CancelButton_Click(null, null);
            }
        }

        void sellSaveLoad()
        {
            if (sts.Count == 0)
            {
                dm.getDS().GetSaveSell(le =>
                {
                    if (le.Value.Count > 0)
                    {
                        foreach (var item in le.Value)
                        {
                            sts.Add(item);
                        }
                        displaySum();
                    }
                }, null);
            }
            else
            {
                dm.getDS().SetSaveSell(sts.ToList(), ls =>
                {
                    CancelButton_Click(null, null);
                }, null);
            }
        }

        void bt_刷新商品库_Click(object sender, RoutedEventArgs e)
        {
            refresh();
        }

        AsyncOperation asyncOper = AsyncOperationManager.CreateOperation(null);
        void refresh()
        {
            dm.getDS().Load(dm.getDS().GetPdTablesQuery(), lo =>
            {
                if (!lo.HasError && lo.Entities.Count() > 0)
                {
                    bindingTreeView(lo.Entities.ToList());
                    cbb_分类.DataContext = dm.getDS().PdTables.GroupBy(p => p.p_商品类别).Select(p => p.First());
                    asyncOper.Post(result =>
                    {
                        Dispatcher.BeginInvoke(() => { tv_分类.ExpandAll(); });
                    }, null);
                }
            }, null);
        }

        void bindingTreeView(List<Web.PdTable> data)
        {
            List<tvObj> tvs = new List<tvObj>();
            var dispds = data.GroupBy(p => p.p_商品类别).Select(p => p.First());
            foreach (var item in dispds)
            {
                var obj = new tvObj();
                obj.Name = item.p_商品类别;
                obj.Children = data.Where(p => p.p_商品类别.Equals(item.p_商品类别)).ToList();
                tvs.Add(obj);
            }
            tv_分类.DataContext = tvs;
        }

        void tb_快速查询_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var si = tv_分类.GetSelectedContainer();
            if (si != null)
            {
                si.IsSelected = false;
            }
        }

        void bt_添加消费_Click(object sender, RoutedEventArgs e)
        {
            addOrder();
        }

        void tv_分类_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount == 2)
            {
                var pd = tv_分类.SelectedItem as Web.PdTable;
                if (pd != null)
                {
                    opAdd(pd);
                    if (tb_快速查询.Text != string.Empty)
                    {
                        tb_快速查询.SelectedItem = string.Empty;
                        tb_快速查询.Text = string.Empty;
                    }
                }
            }    
        }

        void bt_选中减一_Click(object sender, RoutedEventArgs e)
        {
            if (dg_ods.Selection.SelectedRows.Count == 1)
            {
                var od = dg_ods.Selection.SelectedRows.First().DataItem as Web.SellDetail;
                od.sd_数量 -= 1;
                od.sd_小计 = (od.sd_数量 * od.sd_单价) * Convert.ToDecimal(od.sd_折扣);
                if (od.sd_数量 <= 0)
                {
                    sts.Remove(od);
                }
                displaySum();
            }
        }

        void bt_选中加一_Click(object sender, RoutedEventArgs e)
        {
            if (dg_ods.Selection.SelectedRows.Count == 1)
            {
                var od = dg_ods.Selection.SelectedRows.First().DataItem as Web.SellDetail;
                od.sd_数量 += 1;
                od.sd_小计 = (od.sd_数量 * od.sd_单价) * Convert.ToDecimal(od.sd_折扣);
                displaySum();
            }
        }

        void bt_选中加数量_Click(object sender, RoutedEventArgs e)
        {
            if (dg_ods.Selection.SelectedRows.Count == 1)
            {
                var od = dg_ods.Selection.SelectedRows.First().DataItem as Web.SellDetail;
                od.sd_数量 += (decimal)tb_数量.Value;
                od.sd_小计 = (od.sd_数量 * od.sd_单价) * Convert.ToDecimal(od.sd_折扣);
                displaySum();
            }
        }

        void bt_赠送_Click(object sender, RoutedEventArgs e)
        {
            if (dg_ods.Selection.SelectedRows.Count == 1)
            {
                var od = dg_ods.Selection.SelectedRows.First().DataItem as Web.SellDetail;
                if (od.sd_小计 != 0)
                {
                    od.sd_小计 = 0;
                }
                else
                {
                    od.sd_小计 = (od.sd_数量 * od.sd_单价) * Convert.ToDecimal(od.sd_折扣);
                }
                displaySum();
            }
        }

        void tb_数量_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                addOrder();
                tb_快速查询.Focus();
            }
        }

        void bt_消费退单_Click(object sender, RoutedEventArgs e)
        {
            if (dg_ods.Selection.SelectedRows.Count == 1)
            {
                sts.Remove(dg_ods.Selection.SelectedRows.First().DataItem as Web.SellDetail);
                displaySum();
            }
        }

        void cbb_分类_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbb_分类.SelectedIndex != -1)
            {
                var tvitem = tv_分类.GetContainers().Where(d => ((tvObj)d.Header).Name.Equals((cbb_分类.SelectedItem as Web.PdTable).p_商品类别)).First();
                tvitem.IsSelected = true;
                TreeViewItemAutomationPeer trvItemAutomation = (TreeViewItemAutomationPeer)TreeViewItemAutomationPeer.CreatePeerForElement(tvitem);
                IScrollItemProvider scrollingAutomationProvider = (IScrollItemProvider)trvItemAutomation.GetPattern(PatternInterface.ScrollItem);
                scrollingAutomationProvider.ScrollIntoView();
            }
        }

        cwin_setPrice PriceWin;
        void bt_指定单价_Click(object sender, RoutedEventArgs e)
        {
            if (dg_ods.Selection.SelectedRows.Count == 1)
            {
                PriceWin = new cwin_setPrice();
                PriceWin.Closed += new EventHandler(PriceWin_Closed);
                PriceWin.tb_售价.Value = (double)(dg_ods.Selection.SelectedRows.First().DataItem as Web.SellDetail).sd_单价;
                PriceWin.Show();
            }
        }

        void PriceWin_Closed(object sender, EventArgs e)
        {
            var cwin = sender as cwin_setPrice;
            cwin.Closed -= new EventHandler(PriceWin_Closed);
            if (cwin.DialogResult.Value)
            {
                var od = dg_ods.Selection.SelectedRows.First().DataItem as Web.SellDetail;
                od.sd_单价 = (decimal)cwin.tb_售价.Value;
                od.sd_小计 = od.sd_数量 * od.sd_单价;
                od.sd_折扣 = 1;
                displaySum();
            }
        }

        protected override void OnOpened()
        {
            base.OnOpened();
            tb_快速查询.Focus();
            if (tb_快速查询.Text != null)
            {
                tb_快速查询.SelectedItem = string.Empty;
                tb_快速查询.Text = string.Empty;
            }
            refresh();
        }

        void tb_快速查询_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                addOrder();
            }
        }

        void tb_快速查询_Populating(object sender, PopulatingEventArgs e)
        {
            AutoCompleteBox source = (AutoCompleteBox)sender;
            dm.getDS().GetPdFilter(e.Parameter, lo =>
            {
                if (!lo.HasError)
                {
                    var pds = new List<Web.PdTable>(lo.Value);
                    source.DataContext = from p in pds
                                         select new autoPd
                                         {
                                             pdName = p.p_商品编号 + "," + p.p_商品名称 + "," + p.p_拼音简码,
                                             pd = p
                                         };
                    source.PopulateComplete();
                }
            }, null);
        }

        void addOrder()
        {
            if (tb_快速查询.Text != string.Empty)
            {
                var pd = dm.getDS().PdTables.Where(p => p.p_条形码.Equals(tb_快速查询.Text));
                if (pd.Count() == 1)
                {
                    opAdd(pd.First());
                    tb_快速查询.SelectedItem = string.Empty;
                    tb_快速查询.Text = string.Empty;
                    return;
                }
                else if (pd.Count() > 1)
                {
                    tb_快速查询.PopulateComplete();
                }
            }

            if (tb_快速查询.SelectedItem != null)
            {
                var pd = tb_快速查询.SelectedItem as autoPd;
                if (pd != null)
                {
                    opAdd(pd.pd);
                    tb_快速查询.SelectedItem = string.Empty;
                    tb_快速查询.Text = string.Empty;
                    return;
                }
            }
            if (tv_分类.SelectedItem != null)
            {
                var spd = tv_分类.SelectedItem as Web.PdTable;
                if (spd != null)
                {
                    opAdd(spd);
                    return;
                }
            }
        }

        void opAdd(Web.PdTable pd)
        {
            var od = sts.FirstOrDefault(o => o.sd_商品名称.Equals(pd.p_商品名称));
            if (od != null)
            {
                if (tb_数量.Value <= 0)
                {
                    od.sd_数量 += 1;
                }
                else
                {
                    od.sd_数量 += (decimal)tb_数量.Value;
                }
                od.sd_小计 = (od.sd_数量 * od.sd_单价) * Convert.ToDecimal(od.sd_折扣);
            }
            else
            {
                var ods = new Web.SellDetail();
                ods.sd_单价 = pd.p_单价;
                ods.sd_商品名称 = pd.p_商品名称;
                ods.sd_商品编号 = pd.p_商品编号;
                ods.sd_单位 = pd.p_单位;
                ods.sd_折扣 = pd.p_折扣;
                if (tb_数量.Value <= 0)
                {
                    ods.sd_数量 = 1;
                }
                else
                {
                    ods.sd_数量 = (decimal)tb_数量.Value;
                }
                ods.sd_小计 = (ods.sd_数量 * ods.sd_单价) * Convert.ToDecimal(ods.sd_折扣);
                sts.Add(ods);
            }
            displaySum();
            tb_数量.Value = 0;
        }

        void displaySum()
        {
            dg_ods.Refresh();
            comput();
        }

        void cwin_SellAdd_Loaded(object sender, RoutedEventArgs e)
        {
            cb_自动小票.IsChecked = other.o_自动打印小票;
            cb_自动小票.Checked += new RoutedEventHandler(cb_自动小票_Checked);
            cb_自动小票.Unchecked += new RoutedEventHandler(cb_自动小票_Unchecked);
            dg_ods.AutoGeneratingColumn += dg_ods_AutoGeneratingColumn;
            sts = new ObservableCollection<Web.SellDetail>();
            dg_ods.DataContext = sts;
            dm.getDS().GetST(lo => { dp_消费时间.DateTime = lo.Value; }, null);
        }

        void cb_自动小票_Unchecked(object sender, RoutedEventArgs e)
        {
            other.o_自动打印小票 = false;
        }

        void cb_自动小票_Checked(object sender, RoutedEventArgs e)
        {
            other.o_自动打印小票 = true;
        }

        void dg_ods_AutoGeneratingColumn(object sender, C1.Silverlight.DataGrid.DataGridAutoGeneratingColumnEventArgs e)
        {
            if (e.Property.PropertyType.Equals(typeof(decimal)) || e.Property.PropertyType.Equals(typeof(double)))
            {
                e.Column.Format = "0.##";
            }
            #region 减少列
            string headername = e.Column.Header.ToString();
            switch (headername)
            {
                // Cancel the columns you don't want to generate.
                case "单位":
                case "操作员":
                case "ID":
                case "外键":
                case "进货价":
                    e.Cancel = true;
                    break;

                case "小计":
                    DataGridAggregate.SetAggregateFunctions(e.Column, new DataGridAggregatesCollection { new DataGridAggregateSum() });
                    break;
                case "数量":
                    DataGridAggregate.SetAggregateFunctions(e.Column, new DataGridAggregatesCollection { new DataGridAggregateSum() });
                    break;
            }
            #endregion
        }

        internal Web.SellTable nsell;
        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            if (sts != null && sts.Count > 0)
            {
                if ((tb_现金.Value + tb_信用卡.Value) < Convert.ToDouble(sts.Sum(p => p.sd_小计)) * tb_折扣.Value)
                {
                    return;
                }
                nsell = new Web.SellTable();
                nsell.st_操作员 = WebContext.Current.User.Name; 
                nsell.st_消费金额 = sts.Sum(o => o.sd_小计);
                nsell.st_整单折扣 = tb_折扣.Value;
                nsell.st_消费时间 = dp_消费时间.DateTime.Value;
                nsell.st_实付金额 = Convert.ToDecimal(nsell.st_整单折扣) * nsell.st_消费金额;
                nsell.st_刷卡支付 = Convert.ToDecimal(tb_信用卡.Value);
                nsell.st_现金支付 = nsell.st_实付金额 - nsell.st_刷卡支付;
                nsell.st_流水号 = nsell.st_消费时间.Ticks.ToString();
                foreach (var item in sts)
                {
                    var pd = dm.getDS().PdTables.FirstOrDefault(p => p.p_商品名称.Equals(item.sd_商品名称));
                    if (pd != null)
                    {
                        item.sd_进货价 = pd.p_进货价;
                        pd.p_库存数量 -= item.sd_数量;
                    }
                    nsell.SellDetails.Add(item);
                }
                dm.getDS().SellTables.Add(nsell);
                dm.getDS().SubmitChanges(le =>
                {
                    this.DialogResult = true;
                }, null);
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            dm.getDS().RejectChanges();
            this.DialogResult = false;
        }
    }
    public class tvObj
    {
        public tvObj()
        {
            Children = new List<Web.PdTable>();
        }
        public string Name { get; set; }
        public List<Web.PdTable> Children { get; set; }
    }
}

